package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.CommonBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.OrderCreateActivity;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.item.CtTextView;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ImageFetcherManager;
import com.cuitrip.util.MediaFetcher;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.GetImageHelper;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.imageupload.imp.OssService;
import com.lab.utils.imageupload.model.OssTokenObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * Created by sheena on 16/2/26.
 */
public class BookingCompleteUserInfoActivity extends CustomUiFragmentActivity implements IProxyCallback{

    @Bind(R.id.tv_upload_hint)
    CtTextView tvUploadHint;

    @Bind(R.id.civ_pic)
    CircleImageView civUploadPic;

    @Bind(R.id.tv_male)
    TextView tvMale;

    @Bind(R.id.tv_female)
    TextView tvFemale;

    @Bind(R.id.il_city_choose)
    ItemLayout ilCityChoose;

    @Bind(R.id.it_icon)
    IconTextView itIcon;

    @Bind(R.id.fl_pic_layout)
    FrameLayout flUploadPic;

    @Bind(R.id.tv_submit)
    TextView tvSubmit;

    @Bind(R.id.ll_gender)
    LinearLayout llGender;

    public static final String SERVICE_INFO = "ORDER_SERVICE_INFO";
    public static final String KEY_USER_INFO = "userInfo";
    public static final String GENDER_MALE = "1";
    public static final String GENDER_FEMALE = "2";
    private String mHeadPic;
    private String mGender;
    private String mCity;
    private ImageFetcherManager mImageFetcherManager;
    private OssService ossService = new OssService();
    private String mUploadedAvaUrl;
    private File tempPhotoFile;
    private ApiProxy mApiProxy = new ApiProxy(this);
    private String genderChoose=GENDER_MALE;
    private String cityChose;
    private String cityAbbr;
    private String country;
    private CtUserInfo userInfo;
    private ServiceInfo serviceInfo;
    private String countryName;
    private String address;


    public static void startActivity(Context context, ServiceInfo serviceInfo, CtUserInfo userInfo) {
        Intent intent = new Intent(context, BookingCompleteUserInfoActivity.class).putExtra(SERVICE_INFO, serviceInfo).putExtra(KEY_USER_INFO, userInfo);
        context.startActivity(intent);
    }

    @Override
    public boolean initCloseTopBar() {
        return true;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getIntent() != null) {
            userInfo = (CtUserInfo) getIntent().getSerializableExtra(KEY_USER_INFO);
            serviceInfo = (ServiceInfo) getIntent().getSerializableExtra(SERVICE_INFO);
            if (userInfo != null) {
                mHeadPic = userInfo.getHeadPic();
                mGender = userInfo.getGender();
                mCity = userInfo.getCity();
            }
        }
        super.onCreate(savedInstanceState, R.layout.activity_complete_userinfo);

    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        tvSubmit.setEnabled(false);
        tvMale.setText(getString(R.string.user_attribute_gender_value_male).toUpperCase());
        tvFemale.setText(getString(R.string.user_attribute_gender_value_female).toUpperCase());
        mImageFetcherManager = new ImageFetcherManager(this, ImageFetcherManager.Source.SELF_INFO_SELECT);
        loadUserProfile();
    }


    @OnClick(R.id.itv_close)
    public void close() {
        finish();
    }

    @OnClick(R.id.fl_pic_layout)
    public void uploadPic() {
        tempPhotoFile = MediaFetcher.getTempImageFilePath(AppCoreRuntime.context);
        if (tempPhotoFile == null) {
            return;
        }
        EasyImage.openChooser(this, "", true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK && requestCode== ChooseCityActivity.REQUEST_CHOOSE_LOCATION){
            cityChose = data.getStringExtra(ChooseCityActivity.CITY_NAME_KEY);
            cityAbbr = data.getStringExtra(ChooseCityActivity.CITY_ABBR_KEY);
            country = data.getStringExtra(ChooseCityActivity.COUNTRY_ABBR_KEY);
            countryName = data.getStringExtra(ChooseCityActivity.COUNTRY_NAME_KEY);
            address = data.getStringExtra(ChooseCityActivity.ADDRESS_KEY);
            loadUserProfile();
            return;
        }
        boolean handleActivity = EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                boolean pickImageSuccess = mImageFetcherManager.cropImage(imageFile, tempPhotoFile, null);
                if (!pickImageSuccess) {
                    MessageUtils.showToast(R.string.feedback_data_err);
                }
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
        if (!handleActivity) {
            if (ImageFetcherManager.REQUEST_CODE_CROP_IMAGE == requestCode) {
                if (resultCode == Activity.RESULT_OK) {
                    Bitmap bp = GetImageHelper.getResizedBitmap(this, Uri.fromFile(tempPhotoFile));
                    if (bp != null) {
                        itIcon.setVisibility(View.GONE);
                        civUploadPic.setImageBitmap(bp);
                        updateImage();
                    }
                }
            }
        }

    }

    protected void updateImage() {
        showLoading();
        CommonBusiness.getMobileOssToken(mApiProxy);
    }

    public void completeAction() {
        Map<String, String> map = new HashMap<>();
        if (mUploadedAvaUrl!=null){
            map.put("headPic", mUploadedAvaUrl);
        }
        map.put("gender", genderChoose);
        if (!TextUtils.isEmpty(address)) {
            map.put("city", address);
        }
        if(!TextUtils.isEmpty(cityAbbr)){
            map.put("cityAbbr",cityAbbr);
        }
        if (!TextUtils.isEmpty(country)){
            map.put("country",country);
        }
        UserBusiness.updateProfile(mApiProxy, map);
    }

    private void loadUserProfile() {
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo == null) {
            return;
        }
        if (mHeadPic != null) {
            ImageHelper.displayImage(mHeadPic, civUploadPic, null);
            tvUploadHint.setVisibility(View.GONE);
            itIcon.setVisibility(View.GONE);
            flUploadPic.setClickable(false);
        } else {
            tvUploadHint.setVisibility(View.VISIBLE);
        }

        llGender.setVisibility(mGender==null?View.VISIBLE:View.GONE);
        if(mCity==null){
            ilCityChoose.setVisibility(View.VISIBLE);
            if(TextUtils.isEmpty(cityChose)){
                ilCityChoose.setleftText(getString(R.string.user_attribute_city_desc));
            }else{
                if (countryName.equals(cityChose)){
                    ilCityChoose.setleftText(cityChose);
                }else {
                    ilCityChoose.setleftText(countryName + "-" + cityChose);
                }

            }
        }else{
            cityChose = userInfo.getCity();
            ilCityChoose.setVisibility(View.GONE);
        }
        tvSubmit.setEnabled(isComplete());

    }

    @OnClick(R.id.tv_male)
    public void chooseMale(){
        tvMale.setBackgroundColor(ResourceUtil.getColor(R.color.orange_ff6855));
        tvMale.setTextColor(ResourceUtil.getColor(R.color.ct_white));
        tvFemale.setBackgroundColor(ResourceUtil.getColor(R.color.ct_white));
        tvFemale.setTextColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
        genderChoose=GENDER_MALE;
    }

    @OnClick(R.id.tv_female)
    public void chooseFemale(){
        tvFemale.setBackgroundColor(ResourceUtil.getColor(R.color.orange_ff6855));
        tvFemale.setTextColor(ResourceUtil.getColor(R.color.ct_white));
        tvMale.setTextColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
        tvMale.setBackgroundColor(ResourceUtil.getColor(R.color.ct_white));
        genderChoose=GENDER_FEMALE;
    }

    @OnClick(R.id.il_city_choose)
    public void chooseCity(){
        TrackUtil.trackScreenName("/user/about/edit/set/city");
        ChooseCityActivity.chooseLocation(this, ChooseCityActivity.PROFILE_MODE,false);
    }

    private boolean isComplete(){
        if (mHeadPic==null || cityChose==null){
            return false;
        }
        return true;
    }

    @OnClick(R.id.tv_submit)
    public void basicInfoSubmit(){
        tvSubmit.setEnabled(true);
        showLoading();
        completeAction();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.MODIFY_USERINFO.equals(response.getApiName())) {
            if (response.isResponseNormal()) {
                if (response.result instanceof CtUserInfo) {
                    CtUserInfo ctUserInfo = (CtUserInfo) response.result;
                    RongIM.getInstance().refreshUserInfoCache(new UserInfo(ctUserInfo.getUid(), ctUserInfo.getNick(), Uri.parse(ctUserInfo.getHeadPic())));
                    hideLoading();
                    OrderCreateActivity.start(this, serviceInfo);
                    finish();
                }
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    hideLoading();
                    MessageUtils.showToast(response.msg);
                }
            }
        } else if (ApiManager.GET_MOBILE_OSS_TOKEN.equals(response.getApiName())) {
            hideLoading();
            if (response.isResponseNormal()) {
                if (response.result instanceof OssTokenObject) {
                    OssTokenObject ossTokenObject = (OssTokenObject) response.result;
                    ossService.initClient(ossTokenObject);
                    CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                    ossService.asyncPutImage(OssService.getObjectName(userInfo.getUid(), tempPhotoFile), tempPhotoFile.getAbsolutePath(), new OssService.UploadCallback() {
                        @Override
                        public void onFailure(String errorMessage) {
                        }

                        @Override
                        public void onSuccess(String url) {
                            mUploadedAvaUrl = url;
                            mHeadPic = url;
                            tvSubmit.setEnabled(isComplete());
                        }

                        @Override
                        public void onProgress(int progress) {
                            AppLog.d("progress" + progress);
                        }
                    });

                }
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }

        }
        return false;
    }

}
